<template>
  <div class="home">
    <!-- <left-menu></left-menu> -->
    <head-nav></head-nav>
    <div class="el-scrollbar" ref="menu_right">
      <div class="menu_content " ref="menu_content">
        <div class="tab-list">
          <el-tabs v-model="activeTab" @tab-click="toPage" type="card" @edit="handleTabs">
            <el-tab-pane v-for="(item,index) in activeTag" :key="item.path" :label="item.title" :name="index.toString()" closable>
            </el-tab-pane>
          </el-tabs>
          <div class="tab-clearall">
            <el-button type="text" icon="close" title="关闭所有" @click="clearAll"></el-button>
          </div>
        </div>
        <div class="current-task" v-if="isTask">
          <!-- <span>当前任务</span> -->
          <el-form label-width="120px">
            <div class="row">
              <div class="col-md-6">
                <el-form-item label="当前任务">
                  <el-select v-model="demandName" :disabled="isDisabled" @clear="setValueNull" clearable filterable placeholder="选择任务">
                    <el-option v-for="item in checktaskarry" :key="item.id" :label="`${item.taskNo}-${item.demandName}`" :value="item.taskNo" @click.native="checktask(item)">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>
        <!-- <div class="tag-list">
          <el-tag
            v-for="(item, index) in activeTag"
            :key="index"
            closable
            @close="handleClose(item)"
            :class="{ tag_content: true, isCurrent: item.path == $route.path }"
          >
            <router-link
              :to="{ path: item.path }"
              @click.native.prevent="toPage(item)"
            >
              <span
                :class="{ isActive: item.path == $route.path, ml5: true }"
                >{{ item.title }}</span
              >
            </router-link>
          </el-tag>
        </div> -->

        <div class="main_content">
          <keep-alive>
            <router-view :key="key" ref="routerView"></router-view>
          </keep-alive>
          <div v-if="subloading" v-loading="subloading" element-loading-text="拼命加载中..." element-loading-spinner="el-icon-loading" class="sub-loading"></div>
        </div>
      </div>
    </div>
    <!-- <footerNav></footerNav> -->
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import HeadNav from './headNav.vue';
import LeftMenu from './leftMenu.vue';
import FooterNav from './footerNav.vue';
import { gettaskList } from '@/api/ruleConfig/groupInfo';

export default {
  data() {
    return {
      isDisabled: false,
      isTask: false, //是否显示选择任务
      checktaskobj: {},
      checktaskarry: [],
      demandName: this.$store.state.checktaskInfo.taskNo,
      activeTag: [],
      activeTab: '',
      routerName: {},
    };
  },
  computed: {
    ...mapGetters(['sidebar', 'checktaskInfo']),
    key() {
      return this.$route.fullPath;
      /* let name =
        this.$route.name !== undefined
          ? this.$route.name +
          new Date().getTime().toString() +
          Math.random().toString()
          : this.$route +
          new Date().getTime().toString() +
          Math.random().toString();
      return name; */
    },
    subloading() {
      return this.$store.state.loading.subloading;
    },
    listData() {
      return this.$store.state.checktaskInfo;
    },
  },

  components: {
    HeadNav,
    LeftMenu,
    FooterNav,
  },
  created() {
    // console.log(this.$store.state.checktaskInfo, "22");
    // this.$set(this,'demandName',this.$store.state.checktaskInfo)
  },
  mounted() {
    this.getRoute();
  },
  methods: {
    // 路由跳转
    toPage() {
      let item = this.activeTag[this.activeTab];
      this.$router.push(item.path);
    },
    handleTabs(targetName, action) {
      // console.log(action);
      if (action === 'remove') {
        // this.activeTag.splice(targetName,1);
        this.handleClose(this.activeTag[parseInt(targetName)]);
      }
    },
    checktask(val) {
      // console.log(val, this.demandName, "val");
      // this.checktaskdes = val.demandName;
      // this.checktaskobj = val;
      // 任务编码+任务名称
      this.$store.commit('updatechecktask', val);
    },
    setValueNull() {
      // (this.checktaskdes = ""), (this.checktaskobj = {});
      this.demandName = '';
      this.$store.commit('updatechecktask', {});
    },
    gettaskListData() {
      gettaskList({}).then((res) => {
        if (res.data.data) {
          this.checktaskarry = res.data.data;
          // console.log(this.$store.state.checktaskInfo.id, "1111111");
          this.checktaskarry.forEach((e) => {
            if (
              this.$store.state.checktaskInfo.id &&
              this.$store.state.checktaskInfo.id == e.id
            ) {
              this.$store.commit('updatechecktask', e);
              // console.log(this.$store.state.checktaskInfo.status, "111");
            }
          });
        }
      });
    },
    handleClose(tag) {
      // console.log(tag);
      if (
        sessionStorage.getItem('tagActive') &&
        JSON.parse(sessionStorage.getItem('tagActive'))
      ) {
        let attr = JSON.parse(sessionStorage.getItem('tagActive'));
        attr.map((item, index) => {
          if (item.path == tag.path) {
            attr.splice(index, 1);
          }
        });
        sessionStorage.setItem('tagActive', JSON.stringify(attr));
      }
      let nextOpenIndex = 0;
      const tagLength = this.activeTag.length;
      let activeTag = this.activeTag.slice(0);
      if (tagLength > 1) {
        activeTag.map((item, index) => {
          // console.log(this.activeTag, item, index, tag.path);
          if (item.path == tag.path) {
            activeTag.splice(index, 1);
            if (tagLength == index + 1) {
              nextOpenIndex = index - 1;
            } else {
              nextOpenIndex = index;
            }
          }
          // delete this.activeTag[index];
        });
      } else if (activeTag.length == 1) {
        activeTag.map((item, index) => {
          if (item.path == tag.path && item.path != '/home') {
            activeTag.splice(index, 1);
          }
        });
      }
      this.activeTab = nextOpenIndex + '';
      this.activeTag = activeTag;
      this.$nextTick(() => {
        if (this.activeTag.length) {
          this.$router.push({ path: this.activeTag[nextOpenIndex].path });
        } else {
          this.$router.push({ path: '/home' });
        }
      });
    },

    // 获取路由 新增tag
    getRoute() {
      this.$store.dispatch('loading/CHNAGE_SUBLOADING', false); // 切换路由 取消加载动画
      let tag = {
        path: this.$route.path,
        icon: this.$route.meta.icon,
        title: this.$route.meta.title,
      };
      // console.log(this.$route);
      if (
        this.$route.meta.title == '规则组' ||
        this.$route.meta.title == '流程管理' ||
        this.$route.meta.title == '险种规则定义'
      ) {
        // console.log(this.$route);
        this.isTask = true;
        if (this.$route.meta.isDisabled) {
          this.isDisabled = true;
        } else {
          this.isDisabled = false;
        }
        this.gettaskListData();
      } else {
        this.isTask = false;
      }
      if (
        sessionStorage.getItem('tagActive') &&
        JSON.parse(sessionStorage.getItem('tagActive'))
      ) {
        this.activeTag = JSON.parse(sessionStorage.getItem('tagActive'));
      }
      // this.activeTag.push(tag);
      let newActiveTag = [...this.activeTag, tag];
      this.activeTag = this.arrayUnique(newActiveTag, 'path');
      // 选中当前      
      for (let i = this.activeTag.length - 1; i >= 0; i--) {
        if (this.activeTag[i].path === tag.path) {
          this.activeTab = i + '';
          break;
        }
      }
      this.$store.dispatch('setTagActive', this.activeTag);
    },

    arrayUnique(arr, name) {
      let hash = {};
      return arr.reduce(function (item, next) {
        hash[next[name]] ? '' : (hash[next[name]] = true && item.push(next));
        return item;
      }, []);
    },
    // 关闭所有tab页
    clearAll() {
      this.activeTag = [{'path': '/home', 'title': '首页'}];
      sessionStorage.setItem('tagActive', JSON.stringify(this.activeTag));
      this.$router.push({ path: '/home' });
    }
  },
  beforeDestroy() { },
  watch: {
    $route: 'getRoute',
    checktaskdes: {
      handler(newval, oldval) {
        // console.log(newval, oldval);
        if (this.checktaskdes != '选择任务') {
          // console.log("222");
          // this.$store.commit('updatechecktask', newval)
        }
      },
      immediate: true,
    },
    activeTag(val, oldVal) {
      // 标识删除了tab栏，需清除keep-alive的缓存数据，否则缓存数据不会自动清除
      if (val && oldVal && val.length < oldVal.length) {
        // 已删除的tab
        this.$nextTick(() => {
          oldVal.forEach(item => {
            for (let i = val.length - 1; i > -1; i--) {
              if (val[i].path === item.path) {
                return false;
              }
            }
            let cache = this.$refs.routerView.$vnode.parent.componentInstance.cache;
            let keys = this.$refs.routerView.$vnode.parent.componentInstance.keys;
            if (cache[item.path]) {
              if (keys.length) {
                let index = keys.indexOf(item.path);
                if (index > -1) {
                  keys.splice(index, 1);
                }
              }
              delete cache[item.path];
            }
            return true;
          })
        })
      }
    }
  },
};
</script>
<style scoped lang='less'>
.current-task {
  margin: 20px 0 0;
  /* span {
    display: inline-block;
    width: 110px;
    font-size: 14px;
    text-align: right;
    // font-weight: 900;
    // margin-right: 10px;
  }
  .el-dropdown span {
    font-size: 14px;
    // color: #ff0000;
  } */
}
.home {
  .menu_right {
    overflow: auto;
    position: absolute;
    right: 0;
    top: 80px;
    // bottom:0;
    bottom: 40px;
    // background:#fff;
    background: #f9f9f9; //2020-0317
  }
  .menu_content {
    position: relative;
    margin: 10px auto 0 auto;
    width: 98%;
    min-width: 1120px;
    box-sizing: border-box;
    // background: #fafafa;
    padding: 0 16px;
  }
  .menu_tag_list {
    margin-bottom: -1px;

    .tag_content {
      height: 33px;
      line-height: 33px;
      // border-bottom: none;
      border-color: #e5e5e5;
      padding: 0 15px !important;

      .svg-icon {
        font-size: 12px;
      }
    }

    .isCurrent {
      background: #fef0f0;
      border-color: #fdbdbd;
    }
  }

  .main_content {
    padding: 15px 0;
  }
}
.tab-list {
  position: relative;
  margin: 0;

  .el-tabs {
    width: calc(100% - 30px);

    /deep/ .el-tabs__header {
      height: 30px;
      margin-bottom: 0;  
    }
  }

  .tab-clearall {
    position: absolute;
    top: 0;
    right: 0;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-bottom: 1px solid #5d9cec;
  }
}
</style>
